package furniture.Controller.Background;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import framework.base.common.Pager;
import framework.base.controller.BaseController;
import furniture.Bean.DingdanBean;
import furniture.Bean.UserBean;
import furniture.Common.Impl.CommonFunImpl;
import furniture.Service.IDingdanService;
import furniture.Service.IUserService;
import furniture.Common.Impl.FileOperateUtilImpl;

@Controller
@RequestMapping("/b_dingdan")
public class DingdanController extends BaseController{

	/**
	 * 订单控制层
	 */
	private static final long serialVersionUID = 1L;
	
	@Autowired
	IDingdanService dingdanService;
	
	@Autowired
	IUserService userService;
	

	@Override
	public void setLogger() {
		
	}
	
	@RequestMapping("/index")
	public ModelAndView index(DingdanBean bean,Pager<DingdanBean> pager){
		ModelAndView modelAndView = new ModelAndView("background/dingdan/index");
		if(null != bean.getDdtime() && !"".equals(bean.getDdtime())){
			bean.setDdtime(bean.getDdtime() + " 00:00:00");
		}
		if(null != bean.getInserttime() && !"".equals(bean.getInserttime())){
			bean.setInserttime(bean.getInserttime() + " 23:59:59");
		}
		pager = dingdanService.selectPage(bean, pager);
		modelAndView.addObject("pager", pager);
		modelAndView.addObject("bean",bean);
		
		double count = 0;
		for (int i = 0; i < pager.getPageList().size(); i++) {
			try {
				count += Double.parseDouble(pager.getPageList().get(i).getPrice());
			} catch (Exception e) {
				// TODO: handle exception
			}
			
		}
		modelAndView.addObject("count", count);
		
		return modelAndView;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(){
		ModelAndView modelAndView = new ModelAndView("background/dingdan/add");
		UserBean userBean = new UserBean();
		userBean.setUtype("2");
		List<UserBean> userList = userService.selectList(userBean);
		modelAndView.addObject("userList", userList);
		
		List<String> quyuList = new ArrayList<String>();
		for (int i = 0; i < userList.size(); i++) {
			if (userList.get(i).getAddress() != null && userList.get(i).getAddress() != "") {
				if (!quyuList.contains(userList.get(i).getAddress())) {
					quyuList.add(userList.get(i).getAddress());
				}
			}
		}
		modelAndView.addObject("quyuList", quyuList);
		return modelAndView;
	}
	
	@RequestMapping("/edit")
	public ModelAndView edit(DingdanBean bean){
		ModelAndView modelAndView = new ModelAndView("background/dingdan/edit");
		bean = dingdanService.selectOne(bean);
		modelAndView.addObject("bean", bean);
		
		UserBean ub = new UserBean();
		ub.setId(bean.getUserid());
		ub = userService.selectOne(ub);
		modelAndView.addObject("quyu", ub.getAddress());
		
		UserBean userBean = new UserBean();
		userBean.setUtype("2");
		List<UserBean> userList = userService.selectList(userBean);
		modelAndView.addObject("userList", userList);
		
		List<String> quyuList = new ArrayList<String>();
		for (int i = 0; i < userList.size(); i++) {
			if (userList.get(i).getAddress() != null && userList.get(i).getAddress() != "") {
				if (!quyuList.contains(userList.get(i).getAddress())) {
					quyuList.add(userList.get(i).getAddress());
				}
			}
		}
		modelAndView.addObject("quyuList", quyuList);
		
		return modelAndView;
	}
	
	@RequestMapping("/insert")
	public void insert(DingdanBean bean,String quyu, HttpServletResponse response){
		response.setContentType("text/html");
		bean.setId(CommonFunImpl.uuid("D"));
		bean.setDdtime(CommonFunImpl.currentTime(1));
		bean.setInserttime(bean.getDdtime());
		
		String arr[] = bean.getUsername().split(";");
		bean.setUsername(arr[1]);
		bean.setUserid(arr[0]);
		if ("".equals(bean.getPrice())) {
			bean.setPrice(null);
		}
		
		String ret = dingdanService.insert(bean) > 0 ? "1" : "0";
		if("1".equals(ret))
		{
			/*添加cookie  -userid*/
			Cookie c = new Cookie("userid", bean.getUserid());//经销商编号
			response.addCookie(c);
			
			String arr_quyu[] = quyu.split(";");
			Cookie c2 = new Cookie("quyu",arr_quyu[0]);
			response.addCookie(c2);
		}
		JSONObject jb = new JSONObject();
		jb.put("ret", ret);
		ret = jb.toString();
		try {
			PrintWriter out = response.getWriter();
			out.print(ret);
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping("/update")
	public void update(DingdanBean bean, HttpServletResponse response){
		response.setContentType("text/html");
		bean.setInserttime(CommonFunImpl.currentTime(1));
		String arr[] = bean.getUsername().split(";");
		bean.setUsername(arr[1]);
		bean.setUserid(arr[0]);
		if ("".equals(bean.getPrice())) {
			bean.setPrice(null);
		}
		String ret = dingdanService.update(bean) > 0 ? "1" : "0";
		JSONObject jb = new JSONObject();
		jb.put("ret", ret);
		ret = jb.toString();
		try {
			PrintWriter out = response.getWriter();
			out.print(ret);
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	@RequestMapping("/delete")
	public void Delete(DingdanBean bean, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		String ret = dingdanService.delete(bean) > 0 ? "1" : "0";
		// 以流的形式返回
		try {
			PrintWriter out = response.getWriter();
			out.print(ret);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 根据区域查询用户
	 */
	@RequestMapping("/quyu")
	public void getUserbyQuyu(String quyu,HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		String arr_quyu[] = quyu.split(";");
		quyu = arr_quyu[1];
		UserBean bean = new UserBean();
		bean.setUtype("2");
		quyu = "全部区域".equals(quyu) ? null : quyu;
		bean.setAddress(quyu);
		List<UserBean> listU = userService.selectList(bean);
		JSONObject jb = new JSONObject();
		jb.put("listU", listU);
		try {
			PrintWriter out = response.getWriter();
			out.print(jb.toString());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 用户
	 */
	@RequestMapping("/c_index")
	public ModelAndView c_index(String year,String month,HttpSession session,DingdanBean bean){
		ModelAndView modelAndView = new ModelAndView("front/dingdan/index");
		String tj = "";
		if (year == null || "".equals(year)) {
			Calendar calendar = Calendar.getInstance();
			year = Integer.toString(calendar.get(Calendar.YEAR)) + "年";
		}
		else{
			tj = year.substring(0,4);
		}
		if (!(month == null || "".endsWith(month))) {
			tj +="-";
			tj +=month.substring(0,2);
		}
		modelAndView.addObject("year", year);
		modelAndView.addObject("month", month);
		
		UserBean userBean = (UserBean)session.getAttribute("user_session");
		bean.setUserid(userBean.getId());
		bean.setDdtime(tj);
		List<DingdanBean> list = dingdanService.selectList(bean);
		modelAndView.addObject("list", list);
		double count = 0;
		for (int i = 0; i < list.size(); i++) {
			try {
				count += Double.parseDouble(list.get(i).getPrice());
			} catch (Exception e) {
				// TODO: handle exception
			}
			
		}
		modelAndView.addObject("count", count);
		return modelAndView;
	}
	
	@RequestMapping("/c_info")
	public ModelAndView c_info(String info){
		ModelAndView modelAndView = new ModelAndView("front/dingdan/info");
		modelAndView.addObject("info", info);
		return modelAndView;
	}
	
	@RequestMapping("/download")
	public void download(String storeName,String realName,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception  {
		String contentType = "application/octet-stream";
		String tmp = storeName.substring(storeName.lastIndexOf("."));
		realName += tmp;
		FileOperateUtilImpl.download(request, response, storeName, contentType,realName);
	}

}
